package com.coc.action;

import com.coc.bean.CcEloUser;
import com.coc.bean.CcMap;
import com.coc.bean.CcUser;
import com.coc.bean.CocSetting;
import com.coc.dao.EloUserDAO;
import com.coc.util.MemCacheUtil;
import com.coc.util.PubFun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Login extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		EloUserDAO sud = (EloUserDAO) getBean("eloUserDAO");
		CocSetting ss = sud.findcs();
		String sns = ss.getSnstype();
		String iid = "";
		String via = request.getParameter("via");
		if (via == null) {
			via = "";
		}
		if (sns.equals("qq")) {
			String payver = request.getParameter("payver");
			if ((payver != null) && (payver.equals("2.0"))) {
				RequestDispatcher rdq = request
						.getRequestDispatcher("pay2.jsp");
				rdq.forward(request, response);
				return;
			}

			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("UTF-8");
			try {
				String openid = request.getParameter("openid");
				String openid1 = request.getParameter("openid");
				String openkey = request.getParameter("openkey");
				String pfkey = request.getParameter("pfkey");
				String pf = request.getParameter("pf");
				String apppath = "";
				if (pf == null) {
					pf = "qzone";
					apppath = ss.getAppurl();
				}
				int hasSendRequest = 0;
				if (pf.equals("qzone")) {
					apppath = ss.getAppurl();
				} else if (pf.equals("pengyou")) {
					apppath = ss.getPyurl();
				} else {
					apppath = ss.getQwburl();
				}
				String params = "";
				String lan = "";
				String APP_ID = ss.getAppid();
				String APP_KEY = ss.getAppkey();
				String APP_NAME = ss.getAppsecret();
				String v3proxy = ss.getV3proxy();
				String v3ip = ss.getV3ip();
				if (v3proxy != null)
					v3proxy.length();

				String URL_REST_SERVER_v3 = "http://" + v3ip;

				int isfan = 0;

				String _token_v3 = PubFun.getV3LikeResult(request, openid1,
						openkey, pf);
				JSONObject jsonobj_v3 = JSONObject.fromObject(_token_v3);
				String ret = jsonobj_v3.getString("ret");
				isfan = Integer.parseInt(jsonobj_v3.getString("is_fans"));

				if (request.getParameter("via") != null) {
					params = params + "&iva=" + request.getParameter("iva");
				}
				if (request.getParameter("gid") != null) {
					params = params + "&gid=" + request.getParameter("gid");
				}

				if (request.getParameter("testno") != null) {
					params = params + "&testno="
							+ request.getParameter("testno");
				}
				if (request.getParameter("lan") != null) {
					lan = request.getParameter("lan");
					params = params + "&lan=" + request.getParameter("lan");
				}
				_token_v3 = PubFun.getV3UserResult(request, openid1, openkey,
						pf);
				ret = jsonobj_v3.getString("ret");
				jsonobj_v3 = JSONObject.fromObject(_token_v3);
				ret = jsonobj_v3.getString("ret");

				String nickname = jsonobj_v3.getString("nickname");
				String figureurl = jsonobj_v3.getString("figureurl");
				String is_vip = jsonobj_v3.getString("is_yellow_vip");
				String is_year_vip = jsonobj_v3.getString("is_yellow_year_vip");
				String vip_level = jsonobj_v3.getString("yellow_vip_level");
				int pos = 0;
				for (int i = 0; i < openid.length(); i++) {
					char temp = openid.charAt(i);
					String str = String.valueOf(temp);
					if (!str.equals("0")) {
						pos = i;
						i = 100;
					}
				}
				openid = openid.substring(pos);
				System.out.println("openid:" + openid);
				CcEloUser su = sud.findBySNSID(openid);

				if (su == null) {
					su = new CcEloUser();
					su.setLv(1);
					su.setHtlv(1);
					su.setLasteloid(0);
					su.setLastaction(System.currentTimeMillis());
					su.setLastelotime(0L);
					su.setCup(0);
					su.setSavetime(0L);
					su.setLastportrait(figureurl);
					CcMap cm = new CcMap();
					CcUser cu = new CcUser();
					cm.setCcuser(cu);
					sud.saveOrUpdate(su);
					if (!is_vip.equals("0")) {
						cm.getCcuser().setViplv(
								Integer.valueOf(Integer.parseInt(vip_level)));
					}

					if (!is_year_vip.equals("0")) {
						cm.getCcuser()
								.setViplv(
										Integer.valueOf(Integer
												.parseInt(vip_level) + 100));
					}
					
					cm.setUid(Integer.valueOf(su.getId()));
					cm.getCcuser().setVipstatus(Integer.valueOf(-1));
					cm.getCcuser().setOpenkey(openkey);
					cm.getCcuser().setPfkey(pfkey);
					cm.getCcuser().setSnsname(nickname);
					cm.getCcuser().setPortrait(figureurl);
					cm.getCcuser().setPyname(nickname);
					cm.getCcuser().setPyportrait(figureurl);
					cm.getCcuser().setQwbname(nickname);
					cm.getCcuser().setQwbportrait(figureurl);
					cm.getCcuser().setPf(pf);
					MemCacheUtil.addObject("cm_" + su.getId(), cm);
				} else {
					su.setLastaction(System.currentTimeMillis());
					su.setLastportrait(figureurl);

					sud.saveOrUpdate(su);

					CcMap cm = (CcMap) MemCacheUtil.getObject("cm_"
							+ su.getId());
					if (pf.equals("qzone")) {
						cm.getCcuser().setSnsname(nickname);
						cm.getCcuser().setPortrait(figureurl);
					} else if (pf.equals("pengyou")) {
						cm.getCcuser().setPyname(nickname);
						cm.getCcuser().setPyportrait(figureurl);
					} else {
						cm.getCcuser().setQwbname(nickname);
						cm.getCcuser().setQwbportrait(figureurl);
					}
					cm.getCcuser().setPf(pf);
					MemCacheUtil.setObject("cm_" + su.getId(), cm);
				}
				String token = MD5digest(
						su.getId() + "|" + System.currentTimeMillis())
						.substring(8, 24);
				int result = MemCacheUtil.setSession(su.getId(), token);
				if (result != 1) {
					RequestDispatcher dispatcher = request
							.getRequestDispatcher("/sys_error.jsp");
					dispatcher.forward(request, response);
					return;
				}
				String tk = su.getId() + "_" + token;
				response.addHeader("P3P", "CP=CAO PSA OUR");
				sud.saveOrUpdate(su);
				RequestDispatcher rdq = request
						.getRequestDispatcher("CocLoading.jsp?v=" + ss.getV()
								+ "&apppath=" + apppath + "&via=" + via
								+ "&pf=" + pf + "&hasSendRequest="
								+ hasSendRequest + "&tk=" + tk);
				rdq.forward(request, response);
				return;
			} catch (Exception e) {
				e.printStackTrace();
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/error.jsp");
				dispatcher.forward(request, response);
			}
		}
	}

	public Object getBean(String name) {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
		return ctx.getBean(name);
	}

	public String MD5digest(String message) {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = message.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char[] str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
				str[(k++)] = hexDigits[(byte0 & 0xF)];
			}
			return new String(str);
		} catch (Exception e) {
		}
		return null;
	}

	public String doHttpClientGet(String url) {
		String str = "";
		try {
			HttpClient httpClient = new HttpClient();
			GetMethod getMethod = new GetMethod(url);
			int statusCode = httpClient.executeMethod(getMethod);
			str = getMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	public String doHttpClientPost(String url, String postdata) {
		String str = "";
		try {
			HttpClient httpClient = new HttpClient();
			PostMethod postMethod = new PostMethod(url);
			postMethod.addRequestHeader("Content-Type",
					"application/x-www-form-urlencoded; charset=UTF-8");
			postMethod.setRequestBody(postdata);
			int statusCode = httpClient.executeMethod(postMethod);
			str = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	public String sortPostData(String data) {
		String[] _array = data.split("&");
		Arrays.sort(_array);
		String _data = "";
		for (String _param : _array)
			_data = _data + "&" + _param;
		return _data.substring(1);
	}

	public static String sortPostData_qq(String data) {
		String[] _array = data.split("&");
		Arrays.sort(_array);
		String _data = "";
		for (String _param : _array) {
			_data = _data + "&" + _param;
		}
		return _data.substring(0);
	}

	public String getHttpContent(String url) {
		return getHttpContent(url, "UTF-8");
	}

	public String getHttpContent(String url, String charSet) {
		HttpURLConnection connection = null;
		String content = "";
		try {
			URL address_url = new URL(url);
			connection = (HttpURLConnection) address_url.openConnection();
			connection.setRequestMethod("POST");

			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
			System.setProperty("sun.net.client.defaultReadTimeout", "30000");

			int response_code = connection.getResponseCode();
			if (response_code == 200) {
				InputStream in = connection.getInputStream();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in, charSet));
				String line = null;
				while ((line = reader.readLine()) != null) {
					content = content + line;
				}
				return content;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null)
				connection.disconnect();
		}
		if (connection != null) {
			connection.disconnect();
		}

		return "";
	}
}

/*
 * Location: C:\Work\WorkSpace\classes\ Qualified Name: com.coc.action.Login
 * JD-Core Version: 0.6.2
 */